package com.diandian.backend.entrance.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.diandian.backend.entrance.client.DianDianJingDongHomeClient;
import com.diandian.backend.entrance.client.dto.jingdongHome.BatchQueryUseableInfoReqDTO;
import com.diandian.backend.entrance.constants.EntranceConstant;
import com.diandian.backend.entrance.dto.ClientPermissionCacheDataDTO;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RouterJingdongHomeService {

    private static final Logger logger = LoggerFactory.getLogger(RouterJingdongHomeService.class);

    @Autowired
    private DianDianJingDongHomeClient client;

    public Object execute(ClientPermissionCacheDataDTO clientInfoDTO, String clientKey, String clientSecret, String cmd, JSONObject data)  throws Exception {

        // 批量查询商品库存及可售状态信息
        if(EntranceConstant.ROUTER_JINGDONG_HOME_QUERY_OPEN_USABLE.equals(cmd)){

            logger.info("执行批量查询商品库存及可售状态信息请求，参数: {}", data.toJSONString());

            // 获取配置信息
            String appKey = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_JINGDONG_HOME, EntranceConstant.SETTING_TYPE_JINGDONG_HOME_APPKEY);
            String appSecret = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_JINGDONG_HOME, EntranceConstant.SETTING_TYPE_JINGDONG_HOME_APPSECRET);
            String operator = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_JINGDONG_HOME, EntranceConstant.SETTING_TYPE_JINGDONG_HOME_OPERATOR);
            String belong = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_CLIENT, EntranceConstant.SETTING_TYPE_CLIENT_BELONG);

            if(appKey == null || "".equals(appKey) || appSecret == null || "".equals(appSecret) || belong == null || "".equals(belong)){
                throw new DefaultException("配置缺失");
            }

            // 参数转换
            BatchQueryUseableInfoReqDTO dataDTO = JSON.parseObject(JSON.toJSONString(data), BatchQueryUseableInfoReqDTO.class);

            // 执行请求
            BaseResult resultDTO;
            try{
                resultDTO = client.queryOpenUseable(appKey, appSecret, null, operator, belong, dataDTO);
            } catch (Exception e){
                logger.error("调用美团闪购服务异常", e);
                resultDTO = new BaseResult(500, "服务访问异常", e.getMessage());
            }

            logger.info("批量查询商品库存及可售状态信息请求结果: {}", JSON.toJSONString(resultDTO));

            // 返回结果
            return resultDTO;
        }

        throw new DefaultException("暂不支持此操作");
    }
}
